// 封装获取DOM元素的方法

// 单一元素
function $(selector) {
    return document.querySelector(selector);
}

// 多个元素
function $$(selectorAll) {
    return document.querySelectorAll(selectorAll);
}

// 初始化数据图片
let imgs = {
    small: ['商品1-缩略图.png', '商品2-缩略图.png', '商品3-缩略图.png'],
    middle: ['商品1-中等图.png', '商品2-中等图.png', '商品3-中等图.png'],
    large: ['商品1-高清图.png', '商品2-高清图.png', '商品3-高清图.png'],
}

let container = $('.contianer');
let largeImg = $('.right-img');
let midImg = $('.left-img');
let smallImg = $('.img-list');
let mask = $('.mask');

function initPage() {
    let str = '';
    for (let i = 0; i < imgs.small.length; i++) {
        str += `<li style="background-image: url(./imgs/${imgs.small[i]})"></li>`;
    }

    smallImg.innerHTML = str;
    $('.img-list li').style.border = '1px solid #000';
}

function bindEvent() {
    // 点击事件
    smallImg.onclick = function (e) {
        if (e.target.tagName === 'LI') {
            let lis = $$('li');
            for (let i = 0; i < lis.length; i++) {
                lis[i].style.border = 'none';
            }
            e.target.style.border = '1px solid #000';

            let index = [].indexOf.call(lis, e.target);
            console.log(imgs.middle[index])
            midImg.style.backgroundImage = `url("./imgs/${imgs.middle[index]}")`;
            largeImg.style.backgroundImage = `url("./imgs/${imgs.large[index]}")`;
        }
    }

    // 移动事件
    midImg.onmousemove = function (e) {
        // 让遮罩层和大图展示
        mask.style.opacity = 1;
        largeImg.style.opacity = 1;

        let top = e.clientY - midImg.offsetTop - mask.offsetHeight / 2;
        let left = e.clientX - midImg.offsetLeft - mask.offsetWidth / 2;

        if (top <= 0) {
            top = 0;
        }
        if (left <= 0) {
            left = 0;
        }
        if (left >= midImg.offsetWidth - mask.offsetWidth) {
            left = midImg.offsetWidth - mask.offsetWidth;
        }
        if (top >= midImg.offsetHeight - mask.offsetHeight) {
            top = midImg.offsetHeight - mask.offsetHeight;
        }
        console.log(top, left);
        // console.log();
        mask.style.left = left + 'px';
        mask.style.top = top + 'px';

        largeImg.style.backgroundPositionX = -left + 'px';
        largeImg.style.backgroundPositionY = -top + 'px';
    }

    // 鼠标语出
    midImg.onmouseleave = function (e) {
        // 让遮罩层和大图消失
        mask.style.opacity = 0;
        largeImg.style.opacity = 0;
    }
}

initPage();
bindEvent();